import { defineStore, createPinia } from 'pinia'
import product_data from "../product"

export const useCounterStore = defineStore('counter', {
    state: () => ({
        productList: [],
        cartList: [],
    }),
    getters: {
        brands: (state) => {
            const brands = state.productList.map((item) => item.brand);
            return [...new Set(brands)];
        },
        colors: (state) => {
            const colors = state.productList.map((item) => item.color);
            return [...new Set(colors)];
        },
    },
    actions: {
        // 请求商品列表
        async getProductList() {
            // 真实环境通过 ajax 获取，这里用异步模拟
            await new Promise((resolve) => setTimeout(resolve, 500));
            this.setProductList(product_data);
        },

        // 购买
        async buy() {
            // 真实环境应通过 ajax 提交购买请求后再清空购物列表
            await new Promise((resolve) => setTimeout(resolve, 500));
            this.emptyCart();
        },

        // 添加商品列表
        setProductList(data) {
            this.productList = data;
        },

        // 添加到购物车
        addCart(id) {
            // 先判断购物车是否已有，如果有，数量+1
            const isAdded = this.cartList.find((item) => item.id === id);
            if (isAdded) {
                isAdded.count++;
            } else {
                this.cartList.push({
                    id: id,
                    count: 1,
                });
            }
        },

        // 修改商品数量
        editCartCount(payload) {
            const product = this.cartList.find((item) => item.id === payload.id);
            if (product) {
                product.count += payload.count;
            }
        },

        // 删除商品
        deleteCart(id) {
            const index = this.cartList.findIndex((item) => item.id === id);
            if (index !== -1) {
                this.cartList.splice(index, 1);
            }
        },

        // 清空购物车
        emptyCart() {
            console.log("清空购物车");
            this.cartList.splice(0, this.cartList.length);
        },
    },
});
